import ChooseSkillUIManager from "../ui/choose_skill_ui_manager";
import EndPanelUIManager from "../ui/endpanel_ui_manager";
import ExtraStatUIManager from "../ui/extra_stat_ui_manager";
import LevelListUIManager from "../ui/levellist_ui_manager";
import MessageBoxUIManager from "../ui/message_box_ui_manager"
import PlayerDetailUIManager from "../ui/player_detail_ui_manager";
import SkillListUIManager from "../ui/skilllist_ui_manager";
import TipsUIManager from "../ui/tip_ui_manager"
import { Config } from "../utils/config";
//import TipsUIManager from "../ui/tips_ui_manager"
import { Emitter } from "../utils/emmiter";
import { MessageType } from "../utils/message";
import { Utils } from "../utils/utils";
import DD from "./dynamic_data_manager";
import MainManager from "./main_manager";
import StorageManager from "./storage_manager";
/**
 * UI管理器 控制各个页面的加载
 * 会从resouces/ui下动态加载ui
 */
const { ccclass, property } = cc._decorator
interface OkCalBack {
    (isOK: boolean, param?: {}): void
}
@ccclass
export default class UIManager extends cc.Component {
    static _instance: UIManager = null

    static get instance() {
        if (this._instance == null) {
            this._instance = new UIManager()
        }
        return this._instance
    }
    static Z_ORDER_1: number = 100
    static Z_ORDER_2: number = 200
    static Z_ORDER_3: number = 300
    static Z_ORDER_4: number = 400
    static Z_ORDER_5: number = 500
    static Z_ORDER_6: number = 600
    uinode: cc.Node;
    canvas: cc.Node;
    damageLabelPool: cc.NodePool;
    hpBar: cc.ProgressBar;
    hpLalbe: cc.Label;
    expBar: cc.ProgressBar;
    waveLabel: cc.Label;

    keyLock: { [key: string]: boolean } = {}
    loadUIRes(resUrl: string, depth: number, callBack: any) {
        if (UIManager.instance.keyLock[resUrl] == null) {
            UIManager.instance.keyLock[resUrl] = false
        }
        if (UIManager.instance.keyLock[resUrl] == false) {
            UIManager.instance.keyLock[resUrl] = true

            cc.loader.loadRes(resUrl, cc.Prefab, function (err, prefab) {
                if (err == null) {
                    let newNode = cc.instantiate(prefab) as cc.Node
                    let canvas = cc.director.getScene().getChildByName("Canvas")
                    canvas.addChild(newNode, depth)
                    callBack()

                    if (UIManager.instance.keyLoadTime[resUrl]) {
                        delete UIManager.instance.keyLoadTime[resUrl]
                        //GameManager.instance.clsoeLoadUITip()
                    }

                    delete UIManager.instance.keyLock[resUrl]
                } else {
                    console.error('加载失败', err, resUrl)
                    UIManager.instance.keyLock[resUrl] = false
                }
            })
        }
    }

    findUI() {
        // 创建对象池
        this.damageLabelPool = new cc.NodePool();
        this.canvas = cc.find('Canvas')
        // 预先生成 100 个节点放入对象池
        for (let i = 0; i < 500; i++) {
            const labelNode = new cc.Node();
            const label = labelNode.addComponent(cc.Label);
            label.fontSize = 36;
            labelNode.color = cc.Color.RED;
            this.damageLabelPool.put(labelNode);
        }
        this.uinode = cc.find('Canvas/UI')
        this.expBar = cc.find('Canvas/UI/expbar').getComponent(cc.ProgressBar);
        let playerDAta = StorageManager.instance.playerData;
        cc.find('Canvas/UI/returnBtn').on("click", this.returnToLevelList, this)
        this.waveLabel = cc.find('Canvas/UI/waveLabel').getComponent(cc.Label);
        this.expBar.progress = playerDAta.curExp / StorageManager.instance.levelExpMap[playerDAta.level]; // 设置进度条
        this.hpBar = cc.find('Canvas/UI/hpbar').getComponent(cc.ProgressBar);
        this.hpLalbe = this.hpBar.getComponentInChildren(cc.Label)
        this.hpBar.progress = StorageManager.instance.playerData.hp / StorageManager.instance.playerData.maxHp; // 设置进度条
        this.expBar.progress = playerDAta.curExp / StorageManager.instance.levelExpMap[playerDAta.level];
        Emitter.register(MessageType.uiUpdate, (name, data) => {
            this.waveLabel.string = "第" + MainManager.instance.curWave + '/' + MainManager.instance.ids.length + '波';
            this.expBar.progress = playerDAta.curExp / StorageManager.instance.levelExpMap[playerDAta.level]; // 设置进度条
            this.hpBar.progress = StorageManager.instance.playerData.hp / StorageManager.instance.playerData.maxHp; // 设置进度条
            this.hpLalbe.string = StorageManager.instance.playerData.hp + '/' + StorageManager.instance.playerData.maxHp
        }, '')

        Emitter.register(MessageType.playerLevelUp, (name, data) => {
            UIManager.instance.openUI(ChooseSkillUIManager, { name: Config.uiName.skillChooseUI })

        }, '')

        Emitter.register(MessageType.gameEnd, (name, data) => {
            cc.log('gamedn')
            MainManager.instance.resetAllInfo()
            UIManager.instance.openUI(EndPanelUIManager, { name: Config.uiName.gameEndUI, param: ['胜利'] })

        }, '')


        Emitter.register(MessageType.gameFail, (name, data) => {
            MainManager.instance.resetAllInfo()
            cc.director.pause()
            UIManager.instance.openUI(EndPanelUIManager, { name: Config.uiName.gameEndUI, param: ['游戏失败'] })

        }, '')

        Emitter.register(MessageType.openSkillList, (name, data) => {
          cc.log('xxxxxxx')
            UIManager.instance.openUI(SkillListUIManager, { name: Config.uiName.skilllistUiManager })

        }, '')

        Emitter.register(MessageType.openCharactor, (name, data) => {
            UIManager.instance.openUI(PlayerDetailUIManager, { name: Config.uiName.chacratorListUI })

        }, '')

        Emitter.register(MessageType.openExtraStat, (name, data) => {
            cc.log('额外')
            // Emitter.fire(MessageType.gameEnd)
             UIManager.instance.openUI(ExtraStatUIManager, { name: Config.uiName.extraStatManager })

        }, '')


        Emitter.register(MessageType.returnToLevelList, (name, data) => {
            UIManager.instance.openUI(LevelListUIManager, { name: Config.uiName.levelListUI })

        }, '')
        UIManager.instance.openUI(LevelListUIManager, { name: Config.uiName.levelListUI })
        // Emitter.fire(MessageType.gameFail)
        // Emitter.register(MessageType.gameEnd, (name, data) => {
        //     UIManager.instance.openUI(ChooseSkillUIManager, { name: Config.uiName.skillChooseUI })

        // }, '')
    }

    showTip(info: string) {
        UIManager.instance.openUI(TipsUIManager, { name: Config.uiName.tipUiManager, param: [info] })
        // TipsUIManager.instance.showTipByIndex(info)
    }

    returnToLevelList() {
        cc.director.pause()
        Emitter.fire(MessageType.returnToLevelList)
        // cc.game.pause();
    }

    showDamage(node: cc.Node, damageValue) {
        // 从对象池获取节点
        let damageLabelNode = this.damageLabelPool.size() > 0
            ? this.damageLabelPool.get()
            : new cc.Node();
        // 设置节点属性
        const label = damageLabelNode.getComponent(cc.Label) || damageLabelNode.addComponent(cc.Label);
        label.string = `-${damageValue}`;
        label.fontSize = 30;
        damageLabelNode.color = cc.Color.RED;
        damageLabelNode.opacity = 255; // 确保完全不透明
        damageLabelNode.zIndex = 3; // 设置一个较高的 zIndex
        // 设置节点初始位置

        // 添加节点到场景中
        const localPosition = Utils.getNodeUsePos1(node)
        damageLabelNode.setPosition(localPosition.x, localPosition.y);
        this.uinode.addChild(damageLabelNode);

        // 播放飘字动画
        // 使用 cc.tween 实现动画
        cc.tween(damageLabelNode)
            .parallel(
                cc.tween().by(1, { position: cc.v2(0, 50) }), // 向上移动 50
                cc.tween().to(1, { opacity: 0 })              // 渐隐
            )
            .call(() => {
                // 动画结束后回收节点
                this.damageLabelPool.put(damageLabelNode);
            })
            .start();
    }


    // showDamage(posx, posy, damageValue) {
    //     // 从对象池获取节点
    //     let damageLabelNode = this.damageLabelPool.size() > 0
    //         ? this.damageLabelPool.get()
    //         : new cc.Node();
    //     // 设置节点属性
    //     const label = damageLabelNode.getComponent(cc.Label) || damageLabelNode.addComponent(cc.Label);
    //     label.string = `-${damageValue}`;
    //     label.fontSize = 30;
    //     damageLabelNode.color = cc.Color.RED;
    //     damageLabelNode.opacity = 255; // 确保完全不透明
    //     damageLabelNode.zIndex = 999; // 设置一个较高的 zIndex
    //     // 设置节点初始位置

    //     // 添加节点到场景中
    //     const localPosition =Utils.getNodeUsePos1()
    //     cc.log(localPosition)
    //     damageLabelNode.setPosition(localPosition.x,localPosition.y);
    //     this.uinode.addChild(damageLabelNode);

    //     // 播放飘字动画
    //     // 使用 cc.tween 实现动画
    //     cc.tween(damageLabelNode)
    //         .parallel(
    //             cc.tween().by(1, { position: cc.v2(0, 50) }), // 向上移动 50
    //             cc.tween().to(1, { opacity: 0 })              // 渐隐
    //         )
    //         .call(() => {
    //             // 动画结束后回收节点
    //             this.damageLabelPool.put(damageLabelNode);
    //         })
    //         .start();
    // }


    preLoadUI() {

        this.loadUIRes('ui/messagebox_ui', UIManager.Z_ORDER_5, function () {

        })

        this.loadUIRes('ui/choose_skill_ui', UIManager.Z_ORDER_4, function () {
            cc.log('load success')
        })
    }
    keyLoadTime: { [key: string]: number } = {}
    updateLoadTime(dt) {
        for (let item in this.keyLock) {
            if (this.keyLock[item] == true) {
                if (this.keyLoadTime[item] == null) {
                    this.keyLoadTime[item] = 0
                }
                if (this.keyLoadTime[item] != -1) {
                    this.keyLoadTime[item] += dt
                    if (this.keyLoadTime[item] > 1 && this.keyLoadTime[item] < 5) {
                        //GameManager.instance.loadingUI()
                    } else if (this.keyLoadTime[item] > 5) {
                        //GameManager.instance.loadUIFail()
                        this.keyLoadTime[item] = -1
                    }
                }
            }
        }
    }
    checkUIIsOpen(uiComponent: any) {
        return (uiComponent.instance && uiComponent.instance.content.active)
    }
    /**
     * 动态打开一个Ui 是实时加载的 可能会卡顿 如果想不卡就在preLoadUI里写进去
     * @param uiComponent 
     * @param param name需要传prefab的名字 param是需要传递的参数
     * @param zIndex 
     */
    openUI(uiComponent: any, param: { name: string, param?: any[] }, zIndex = UIManager.Z_ORDER_2) {
        if (uiComponent.instance) {
            uiComponent.instance.showUI(...param.param)
        } else {
            this.loadUIRes('ui/' + param.name, zIndex, () => {
                uiComponent.instance.showUI(...param.param)
            })
        }
    }
    LoadTipsByStr(desc: string) {
        if (TipsUIManager.instance) {
            TipsUIManager.instance.showTipsByStr(desc)
        } else {
            this.loadUIRes("ui/tips_ui", UIManager.Z_ORDER_6, function () {
                TipsUIManager.instance.showTipsByStr(desc)
            })
        }
    }
    LoadMessageBox(title: string, desc: string, callback: OkCalBack = null, param: {} = null, isNormal: boolean = true, labels: string[] = null) {
        if (MessageBoxUIManager.instance) {
            MessageBoxUIManager.instance.showUI(title, desc, callback, param, isNormal, labels)
        } else {
            this.loadUIRes("ui/messagebox_ui", UIManager.Z_ORDER_4 + 1, function () {
                MessageBoxUIManager.instance.showUI(title, desc, callback, param, isNormal, labels)
            })
        }
    }
}